<?php
/**
 * 砍价活动管理
 * User: Administrator
 * Date: 2017/7/12
 * Time: 15:37
 */
defined('InNcPHP') or exit('Access Invalid!');

class bargainControl extends SystemControl {

    private $links = array(
        array('url'=>'act=bargain&op=index','lang'=>'bargain_index'),
        array('url'=>'act=bargain&op=bargain_add','lang'=>'nc_new')
    );

    public  function __construct()
    {
        parent::__construct();
        Language::read('bargain');
    }

    /**
     * 活动列表
     */
   public function indexOp(){
       $bargin_model = Model('bargain');
       $merchant_model = Model('member_merchant');
       $condition = array();
       if (chksubmit()){
           if (!empty($_POST['del_id'])){
               if (is_array($_POST['del_id'])){
                   foreach ($_POST['del_id'] as $k => $v){
                       $bargin_model->delBargain(array('bargain_id'=>intval($v)));
                   }
               }
               $this->log(L('nc_delete,advert_index_advert_name').'[bargain_id:'.intval($_POST['del_id']).']',1);
               showMessage(L('nc_common_del_succ'));
           }else {
               $this->log(L('nc_delete,advert_index_advert_name').'[bargain_id:'.intval($_POST['del_id']).']',0);
               showMessage(L('nc_common_del_succ'));
           }
       }

       if (isset($_GET['search_title']) && $_GET['search_title']) {
           $condition['bg_title'] = array('like', '%' . trim($_GET['search_title']) . '%');
       }
       if (isset($_GET['search_state']) && is_numeric($_GET['search_state'])) {
           $condition['type'] = intval($_GET['search_state']);
       }
       if (isset($_GET['search_merchant']) && is_numeric($_GET['search_merchant'])) {
           $condition['merchant_id'] = intval($_GET['search_merchant']);
       }
       $bargin_list = $bargin_model->getBarginlistPage($condition,'*','10','bargain_id desc');
       if(is_array($bargin_list)){
           foreach($bargin_list as $k =>$v){
            $bargin_list[$k]['shop_name'] = $merchant_model->getfby_merchant_id($v['merchant_id'], 'mc_shop_name');
           }
       }
       $merchants = $merchant_model->getMerchantList(array('mc_status'=>1), 'merchant_id,mc_shop_name');
       Tpl::output('search', $_GET);
       Tpl::output('merchants',$merchants);
       Tpl::output('bargin_list',$bargin_list);
       Tpl::output('top_link', $this->sublink($this->links, 'index'));
       Tpl::output('page',$bargin_model->showpage());
       Tpl::showpage('bargain.index');
   }

    /**
     * 添加活动
     */

   public function bargain_addOp(){
       $merchant_model = Model('member_merchant');
       $bargin_model = Model('bargain');
       $area_model = Model('area');
       $merchants = $merchant_model->getMerchantList(array('mc_status'=>1), 'merchant_id,mc_shop_name');//获取所有商家
       if(chksubmit()){
           $param = array();
           $param['bg_title']       = $_POST['title'];
           $param['bg_price']       = $_POST['show_price'];
           $param['bg_store']       = $_POST['store'];
           $param['bg_floorprice']  = $_POST['market_price'];
           $param['bg_degree']      = $_POST['degree'];
           $param['bg_detail']      = $_POST['content'];
           $param['start_time']     = strtotime($_POST['search_stime']);
           $param['end_time']       = strtotime($_POST['search_etime']);
           $param['merchant_id']    = $_POST['merchant_id'];
           $param['if_show']        = $_POST['if_show'];
           $param['min_price']      = $_POST['min_price'];
           $param['max_price']      = $_POST['max_price'];
           $param['type']           = $_POST['type'];
           $param['firm_province_id'] = $_POST['province_id'];
           $param['firm_city_id']   = $_POST['city_id'];
           $param['firm_area_id']   = $_POST['area_id'];
           $param['city_name']      = $area_model->getfby_area_id($_POST['city_id'],'name');
           $param['bg_rule']        = $_POST['content1'];
           $param['firm_info']      = $_POST['content2'];
           $param['is_hot']         = $_POST['is_hot'];
           $param['if_code']        = $_POST['if_code'];
           $param['friends_sum']    = $_POST['friend_price'];
           $param['share_sun']      = $_POST['share_sun'];
           $param['bg_rs']          = $_POST['bg_rs'];
           $param['true_sum']       = $_POST['true_sum'];
           $param['add_time']       = time();
          //活动封面图片
           $upload = new UploadFile();
           $upload->set('max_size', 2048);
           $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
           $result = $upload->upfile('thumb');
           if($result){
               $param['bg_thumb'] = $upload->getSysSetPath() . $upload->file_name;
           }else{
               //图片上传失败
               $this->log(L('nc_add,ticket_index_ticket').'[tk_title:'.$_POST['title'].']',0);
               showMessage(L('nc_common_save_fail').$upload->error);
           }
           //商品详情图片
           $upload = new UploadFile();
           $upload->set('max_size', 2048);
           $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
           $result = $upload->upfile('face');
           if($result){
               $param['bg_face'] = $upload->getSysSetPath() . $upload->file_name;
           }else{
               //图片上传失败
               $this->log(L('nc_add,ticket_index_ticket').'[tk_title:'.$_POST['title'].']',0);
               showMessage(L('nc_common_save_fail').$upload->error);
           }
           //二维码LOGO

               $upload = new UploadFile();
               $upload->set('max_size', 2048);
               $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
               $result = $upload->upfile('code_img');
               if($result){
                   $param['code_img'] = $upload->getSysSetPath() . $upload->file_name;
               }else{
                   $param['code_img'] = null;
               }

           $re = $bargin_model ->addBargin($param);
           if($re){
               //将活动信息写入redis 缓存
               $redis = new Redis();
               $deploy = C('redis');
               $redis->connect($deploy['master']['host'],$deploy['master']['port']);
               $name = $deploy['prefix'].'bargain_'.$re;
               $redis->set($name,json_encode($param));
               $this->log(L('nc_add,bargain_index_ticket').'['.$_POST['title'].']',1);
               showMessage(L('nc_common_save_succ'), 'index.php?act=bargain&op=index');
           }else{
               $this->log(L('nc_add,bargain_index_ticket').'['.$_POST['title'].']',0);
               showMessage(L('nc_common_save_fail'));
           }

       }
       $provinces = $area_model->getAreaList(array('parent_id'=>1));//获取省ID
       Tpl::output('provinces',$provinces);
       Tpl::output('merchants',$merchants);
       Tpl::output('top_link',$this->sublink($this->links,'bargain_add'));
       Tpl::showpage('bargain.add');
   }


   /**
    * 编辑活动
    */

    public function bargain_editOp(){
        $merchant_model = Model('member_merchant');
        $bargin_model = Model('bargain');
        $area_model = Model('area');
        if(chksubmit()){
            $bargain_id = $_POST['bargain_id'];
            $param = array();

            $param['bg_title']       = $_POST['title'];
            $param['bg_price']       = $_POST['show_price'];
            $param['bg_store']       = $_POST['store'];
            $param['bg_floorprice']  = $_POST['market_price'];
            $param['bg_degree']      = $_POST['degree'];
            $param['bg_detail']      = $_POST['content'];
            $param['start_time']     = strtotime($_POST['search_stime']);
            $param['end_time']       = strtotime($_POST['search_etime']);
            $param['merchant_id']    = $_POST['merchant_id'];
            $param['if_show']        = $_POST['if_show'];
            $param['min_price']      = $_POST['min_price'];
            $param['max_price']      = $_POST['max_price'];
            $param['type']           = $_POST['type'];
            $param['type']           = $_POST['type'];
            $param['firm_province_id'] = $_POST['province_id'];
            $param['firm_city_id']   = $_POST['city_id'];
            $param['firm_area_id']   = $_POST['area_id'];
            $param['city_name']      = $area_model->getfby_area_id($_POST['city_id'],'name');
            $param['bg_rule']        = $_POST['content1'];
            $param['firm_info']      = $_POST['content2'];
            $param['is_hot']         = $_POST['is_hot'];
            $param['if_code']        = $_POST['if_code'];
            $param['friends_sum']    = $_POST['friend_price'];
            $param['share_sun']      = $_POST['share_sun'];
            $param['bg_rs']          = $_POST['bg_rs'];
            $param['true_sum']       = $_POST['true_sum'];
            $param['add_time']       = time();
            //如果封面有重新上传的话
            if ($_FILES['thumb']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                //封面图片
                $result = $upload->upfile('thumb');
                if($result){
                    //得到图片上传后的路径
                    $param['bg_thumb'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'['.$bargain_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }
            //如果商品详情有重新上传的话
            if ($_FILES['face']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                //封面图片
                $result = $upload->upfile('face');
                if($result){
                    //得到图片上传后的路径
                    $param['bg_face'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'['.$bargain_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }
            //如果二维码有重新上传的话
            if ($_FILES['code_img']['tmp_name']) {
                $upload = new UploadFile();
                $upload->set('max_size', 2048);
                $upload->set('default_dir', 'product/' . $upload->getSysSetPath());
                //封面图片
                $result = $upload->upfile('code_img');
                if($result){
                    //得到图片上传后的路径
                    $param['code_img'] = $upload->getSysSetPath() . $upload->file_name;
                } else {
                    //图片上传失败
                    $this->log(L('nc_edit,ticket_index_ticket').'['.$bargain_id.']',0);
                    showMessage(L('nc_common_save_fail').$upload->error);
                }
            }

            $re = $bargin_model->updateBargin(array('bargain_id'=>$bargain_id),$param);

            if($re){
                //将活动信息写入redis 缓存
                $redis = new Redis();
                $deploy = C('redis');
                $redis->connect($deploy['master']['host'],$deploy['master']['port']);
                $name = $deploy['prefix'].'bargain_'.$bargain_id;
                $redis->set($name,json_encode($param));
                $this->log(L('nc_edit,ticket_index_ticket').'[tk_id:'.$bargain_id.']',1);
                showMessage(L('nc_common_save_succ'), 'index.php?act=bargain&op=index');
            }else{
                $this->log(L('nc_edit,ticket_index_ticket').'[tk_id:'.$bargain_id.']',0);
                showMessage(L('nc_common_save_fail'));
            }
        }
        //获取活动详细信息
        $bg_id = intval($_GET['bargain_id']);
        if(empty($bg_id)){
            showMessage('参数有误', 'index.php?act=bargain&op=index');
        }
        $bargin_info  = $bargin_model->getBargainInfo(array('bargain_id'=>$bg_id));
        $bargin_info['bg_thumb'] = UPLOAD . 'product/' . $bargin_info['bg_thumb'];
        $bargin_info['bg_face']  = UPLOAD . 'product/' . $bargin_info['bg_face'];
        $bargin_info['code_img']  = UPLOAD . 'product/' . $bargin_info['code_img'];
        array_push($this->links, array('url'=>'act=bargain&op=bargain_edit&bargain_id=' . $bg_id,'lang'=>'nc_edit'));
        $merchants = $merchant_model->getMerchantList(array('mc_status'=>1), 'merchant_id,mc_shop_name');
        $provinces = $area_model->getAreaList(array('parent_id'=>1));//获取省ID
        //获取已经选中市、县
        $citys = $area_model->getAreaList(array('parent_id'=>$bargin_info['firm_province_id']));
        $areas = $area_model->getAreaList(array('parent_id'=>$bargin_info['firm_city_id']));
        Tpl::output('citys',$citys);
        Tpl::output('areas',$areas);
        Tpl::output('provinces',$provinces);
        Tpl::output('merchants',$merchants);
        Tpl::output('top_link', $this->sublink($this->links, 'edit'));
        Tpl::output('bargain_info',$bargin_info);
        Tpl::showpage('bargain.edit');

    }

    /**
     * 活动删除
     */

    public  function bargain_delOp(){
        $bargin_model = Model('bargain');
        $bargin_id = $_GET['bargain_id'];
        if(!empty($bargin_id)){
            $bargin_model->delBargain(array('bargain_id'=>$bargin_id));
            //删除缓存
            $redis = Cache::getInstance('redis');
            $name = 'bargain_'.$bargin_id;
            $redis->rm($name);
            $this->del_redis_order_info($bargin_id);
            $this->log(L('nc_delete,advert_index_advert_name').'[bargin_id:'.intval($_GET['bargin_id']).']',1);
            showMessage(L('nc_common_del_succ'));
        }else{
            $this->log(L('nc_delete,advert_index_advert_name').'[advert_id:'.intval($_GET['advert_id']).']',0);
            showMessage(L('nc_common_del_fail'));
        }
    }

    /**
     * 活动开关
     */
    public function bargain_if_showOp(){

        if (!empty($_GET['bargain_id']) && isset($_GET['if_show'])){
            $bargin_model = Model('bargain');
            $bargin_model->updateBargin(array('bargain_id'=>intval($_GET['bargain_id'])), array('if_show'=>$_GET['if_show']));
            $this->log(L('nc_edit,advert_index_advert_name').'[bargain_id:'.intval($_GET['bargain_id']).',state:'.$_GET['if_show'].']',1);
            showMessage(L('nc_common_op_succ'));
        }else {
            $this->log(L('nc_edit,advert_index_advert_name').'[bargain_id:'.intval($_GET['bargain_id']).',state:'.$_GET['if_show'].']',0);
            showMessage(L('nc_common_op_fail'));
        }

    }

    /**
     * @param    $bargain_id
     * 删除redis中属于该活动ID的订单和砍价次数
     *
     */
    private function del_redis_order_info($bargain_id){

        $this->redis = new Redis();
        $this->deploy = C('redis');
        $this->redis->connect($this->deploy['master']['host'],$this->deploy['master']['port']);
        $res = $this->redis->keys($this->deploy['prefix'].'orders*');

        //删除属于该活动的缓存
        foreach($res as $k){
            $order_id = substr($k,12);
            if($this->redis->hGet($k,'bargain_id')==$bargain_id){
                $this->redis->del($k);
                $order_sum_name = $this->deploy['prefix'].'orderu-'.$order_id.'*';
                $kes = $this->redis->keys($order_sum_name);
                $this->redis->del($kes);
            }

        }
    }
}